{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "$$\n",
    "\\def\\CC{\\bf C}\n",
    "\\def\\QQ{\\bf Q}\n",
    "\\def\\RR{\\bf R}\n",
    "\\def\\ZZ{\\bf Z}\n",
    "\\def\\NN{\\bf N}\n",
    "$$\n",
    "# Brief Tour of the Standard Library --- Part II\n",
    "\n",
    "This second tour covers more advanced modules that support professional programming needs. These modules rarely occur in small scripts.\n",
    "\n",
    "## Output Formatting\n",
    "\n",
    "The reprlib module provides a version of repr customized for abbreviated displays of large or deeply nested containers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"{'a', 'c', 'd', 'e', 'f', 'g', ...}\""
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import reprlib\n",
    "reprlib.repr(set('supercalifragilisticexpialidocious'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The pprint module offers more sophisticated control over printing both built-in and user defined objects in a way that is readable by the interpreter. When the result is longer than one line, the \"pretty printer\" adds line breaks and indentation to more clearly reveal data structure:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[[['black', 'cyan'],\n",
       "   'white',\n",
       "   ['green', 'red']],\n",
       "  [['magenta', 'yellow'],\n",
       "   'blue']]]"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pprint\n",
    "t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',\n",
    "    'yellow'], 'blue']]]\n",
    "\n",
    "pprint.pprint(t, width=30)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The textwrap module formats paragraphs of text to fit a given screen width:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "The wrap() method is just like fill()\n",
       "except that it returns a list of strings\n",
       "instead of one big string with newlines\n",
       "to separate the wrapped lines."
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import textwrap\n",
    "doc = \"\"\"The wrap() method is just like fill() except that it returns\n",
    "a list of strings instead of one big string with newlines to separate\n",
    "the wrapped lines.\"\"\"\n",
    "\n",
    "print(textwrap.fill(doc, width=40))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The locale module accesses a database of culture specific data formats. The grouping attribute of locale's format function provides a direct way of formatting numbers with group separators:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'English_United States.1252'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import locale\n",
    "locale.setlocale(locale.LC_ALL, 'English_United States.1252')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1,234,567'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conv = locale.localeconv()          # get a mapping of conventions\n",
    "x = 1234567.8\n",
    "locale.format(\"%d\", x, grouping=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'$1,234,567.80'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "locale.format_string(\"%s%.*f\", (conv['currency_symbol'],\n",
    "                     conv['frac_digits'], x), grouping=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Templating\n",
    "\n",
    "The string module includes a versatile ~string.Template class with a simplified syntax suitable for editing by end-users. This allows users to customize their applications without having to alter the application.\n",
    "\n",
    "The format uses placeholder names formed by `$` with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing `$$` creates a single escaped `$` :"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Nottinghamfolk send $10 to the ditch fund.'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from string import Template\n",
    "t = Template('${village}folk send $$10 to $cause.')\n",
    "t.substitute(village='Nottingham', cause='the ditch fund')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ~string.Template.substitute method raises a KeyError when a placeholder is not supplied in a dictionary or a keyword argument. For mail-merge style applications, user supplied data may be incomplete and the ~string.Template.safe\\_substitute method may be more appropriate ---it will leave placeholders unchanged if data is missing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Traceback (most recent call last):\n",
       "  ...\n",
       "KeyError: 'owner'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t = Template('Return the $item to $owner.')\n",
    "d = dict(item='unladen swallow')\n",
    "t.substitute(d)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Return the unladen swallow to $owner.'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t.safe_substitute(d)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Template subclasses can specify a custom delimiter. For example, a batch renaming utility for a photo browser may elect to use percent signs for placeholders such as the current date, image sequence number, or file format:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f\n"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import time, os.path\n",
    "photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']\n",
    "class BatchRename(Template):\n",
    "    delimiter = '%'\n",
    "fmt = input('Enter rename style (%d-date %n-seqnum %f-format):  ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "t = BatchRename(fmt)\n",
    "date = time.strftime('%d%b%y')\n",
    "for i, filename in enumerate(photofiles):\n",
    "    base, ext = os.path.splitext(filename)\n",
    "    newname = t.substitute(d=date, n=i, f=ext)\n",
    "    print('{0} --> {1}'.format(filename, newname))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_1074.jpg --> Ashley_0.jpg\n",
    "img_1076.jpg --> Ashley_1.jpg\n",
    "img_1077.jpg --> Ashley_2.jpg"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another application for templating is separating program logic from the details of multiple output formats. This makes it possible to substitute custom templates for XML files, plain text reports, and HTML web reports.\n",
    "\n",
    "## Working with Binary Data Record Layouts\n",
    "\n",
    "The struct module provides ~struct.pack and ~struct.unpack functions for working with variable length binary record formats. The following example shows how to loop through header information in a ZIP file without using the zipfile module. Pack codes `\"H\"` and `\"I\"` represent two and four byte unsigned numbers respectively. The `\"<\"` indicates that they are standard size and in little-endian byte order:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import struct\n",
    "\n",
    "with open('myfile.zip', 'rb') as f:\n",
    "    data = f.read()\n",
    "\n",
    "start = 0\n",
    "for i in range(3):                      # show the first 3 file headers\n",
    "    start += 14\n",
    "    fields = struct.unpack('<IIIHH', data[start:start+16])\n",
    "    crc32, comp_size, uncomp_size, filenamesize, extra_size = fields\n",
    "\n",
    "    start += 16\n",
    "    filename = data[start:start+filenamesize]\n",
    "    start += filenamesize\n",
    "    extra = data[start:start+extra_size]\n",
    "    print(filename, hex(crc32), comp_size, uncomp_size)\n",
    "\n",
    "    start += extra_size + comp_size     # skip to the next header"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Multi-threading\n",
    "\n",
    "Threading is a technique for decoupling tasks which are not sequentially dependent. Threads can be used to improve the responsiveness of applications that accept user input while other tasks run in the background. A related use case is running I/O in parallel with computations in another thread.\n",
    "\n",
    "The following code shows how the high level threading module can run tasks in background while the main program continues to run:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import threading, zipfile\n",
    "\n",
    "class AsyncZip(threading.Thread):\n",
    "    def __init__(self, infile, outfile):\n",
    "        threading.Thread.__init__(self)\n",
    "        self.infile = infile\n",
    "        self.outfile = outfile\n",
    "\n",
    "    def run(self):\n",
    "        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)\n",
    "        f.write(self.infile)\n",
    "        f.close()\n",
    "        print('Finished background zip of:', self.infile)\n",
    "\n",
    "background = AsyncZip('mydata.txt', 'myarchive.zip')\n",
    "background.start()\n",
    "print('The main program continues to run in foreground.')\n",
    "\n",
    "background.join()    # Wait for the background task to finish\n",
    "print('Main program waited until background was done.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The principal challenge of multi-threaded applications is coordinating threads that share data or other resources. To that end, the threading module provides a number of synchronization primitives including locks, events, condition variables, and semaphores.\n",
    "\n",
    "While those tools are powerful, minor design errors can result in problems that are difficult to reproduce. So, the preferred approach to task coordination is to concentrate all access to a resource in a single thread and then use the queue module to feed that thread with requests from other threads. Applications using ~queue.Queue objects for inter-thread communication and coordination are easier to design, more readable, and more reliable.\n",
    "\n",
    "## Logging\n",
    "\n",
    "The logging module offers a full featured and flexible logging system. At its simplest, log messages are sent to a file or to `sys.stderr` :"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "logging.debug('Debugging information')\n",
    "logging.info('Informational message')\n",
    "logging.warning('Warning:config file %s not found', 'server.conf')\n",
    "logging.error('Error occurred')\n",
    "logging.critical('Critical error -- shutting down')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This produces the following output:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "WARNING:root:Warning:config file server.conf not found\n",
    "ERROR:root:Error occurred\n",
    "CRITICAL:root:Critical error -- shutting down"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default, informational and debugging messages are suppressed and the output is sent to standard error. Other output options include routing messages through email, datagrams, sockets, or to an HTTP Server. New filters can select different routing based on message priority: ~logging.DEBUG, ~logging.INFO, ~logging.WARNING, ~logging.ERROR, and ~logging.CRITICAL.\n",
    "\n",
    "The logging system can be configured directly from Python or can be loaded from a user editable configuration file for customized logging without altering the application.\n",
    "\n",
    "## Weak References\n",
    "\n",
    "Python does automatic memory management (reference counting for most objects and garbage collection to eliminate cycles). The memory is freed shortly after the last reference to it has been eliminated.\n",
    "\n",
    "This approach works fine for most applications but occasionally there is a need to track objects only as long as they are being used by something else. Unfortunately, just tracking them creates a reference that makes them permanent. The weakref module provides tools for tracking objects without creating a reference. When the object is no longer needed, it is automatically removed from a weakref table and a callback is triggered for weakref objects. Typical applications include caching objects that are expensive to create:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import weakref, gc\n",
    "class A:\n",
    "    def __init__(self, value):\n",
    "        self.value = value\n",
    "    def __repr__(self):\n",
    "        return str(self.value)\n",
    "\n",
    "a = A(10)                   # create a reference\n",
    "d = weakref.WeakValueDictionary()\n",
    "d['primary'] = a            # does not create a reference\n",
    "d['primary']                # fetch the object if it is still alive"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "del a                       # remove the one reference\n",
    "gc.collect()                # run garbage collection right away"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Traceback (most recent call last):\n",
       "  File \"<stdin>\", line 1, in <module>\n",
       "    d['primary']                # entry was automatically removed\n",
       "  File \"C:/python38/lib/weakref.py\", line 46, in __getitem__\n",
       "    o = self.data[key]()\n",
       "KeyError: 'primary'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d['primary']                # entry was automatically removed"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tools for Working with Lists\n",
    "\n",
    "Many data structure needs can be met with the built-in list type. However, sometimes there is a need for alternative implementations with different performance trade-offs.\n",
    "\n",
    "The array module provides an ~array.array() object that is like a list that stores only homogeneous data and stores it more compactly. The following example shows an array of numbers stored as two byte unsigned binary numbers (typecode `\"H\"`) rather than the usual 16 bytes per entry for regular lists of Python int objects:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "26932"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from array import array\n",
    "a = array('H', [4000, 10, 700, 22222])\n",
    "sum(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array('H', [10, 700])"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a[1:3]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The collections module provides a ~collections.deque() object that is like a list with faster appends and pops from the left side but slower lookups in the middle. These objects are well suited for implementing queues and breadth first tree searches:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Handling task1"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from collections import deque\n",
    "d = deque([\"task1\", \"task2\", \"task3\"])\n",
    "d.append(\"task4\")\n",
    "print(\"Handling\", d.popleft())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "unsearched = deque([starting_node])\n",
    "def breadth_first_search(unsearched):\n",
    "    node = unsearched.popleft()\n",
    "    for m in gen_moves(node):\n",
    "        if is_goal(m):\n",
    "            return m\n",
    "        unsearched.append(m)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In addition to alternative list implementations, the library also offers other tools such as the bisect module with functions for manipulating sorted lists:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import bisect\n",
    "scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]\n",
    "bisect.insort(scores, (300, 'ruby'))\n",
    "scores"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The heapq module provides functions for implementing heaps based on regular lists. The lowest valued entry is always kept at position zero. This is useful for applications which repeatedly access the smallest element but do not want to run a full list sort:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[-5, 0, 1]"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from heapq import heapify, heappop, heappush\n",
    "data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]\n",
    "heapify(data)                      # rearrange the list into heap order\n",
    "heappush(data, -5)                 # add a new entry\n",
    "[heappop(data) for i in range(3)]  # fetch the three smallest entries"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Decimal Floating Point Arithmetic\n",
    "\n",
    "The decimal module offers a ~decimal.Decimal datatype for decimal floating point arithmetic. Compared to the built-in float implementation of binary floating point, the class is especially helpful for\n",
    "\n",
    "-   financial applications and other uses which require exact decimal representation,\n",
    "-   control over precision,\n",
    "-   control over rounding to meet legal or regulatory requirements,\n",
    "-   tracking of significant decimal places, or\n",
    "-   applications where the user expects the results to match calculations done by hand.\n",
    "\n",
    "For example, calculating a 5% tax on a 70 cent phone charge gives different results in decimal floating point and binary floating point. The difference becomes significant if the results are rounded to the nearest cent:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Decimal('0.74')"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from decimal import *\n",
    "round(Decimal('0.70') * Decimal('1.05'), 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.73"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "round(.70 * 1.05, 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ~decimal.Decimal result keeps a trailing zero, automatically inferring four place significance from multiplicands with two place significance. Decimal reproduces mathematics as done by hand and avoids issues that can arise when binary floating point cannot exactly represent decimal quantities.\n",
    "\n",
    "Exact representation enables the ~decimal.Decimal class to perform modulo calculations and equality tests that are unsuitable for binary floating point:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Decimal('0.00')"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Decimal('1.00') % Decimal('.10')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.09999999999999995\n"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1.00 % 0.10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum([Decimal('0.1')]*10) == Decimal('1.0')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum([0.1]*10) == 1.0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The decimal module provides arithmetic with as much precision as needed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Decimal('0.142857142857142857142857142857142857')"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "getcontext().prec = 36\n",
    "Decimal(1) / Decimal(7)"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
